<?php
	// Fonctions utiles à ce projet
    
    function addHook($hookName, $hookTime = 'beforeDisplay')
    {
        $hooks = getoption('__hooks__');
        if (null === $hooks)
            $hooks = array();
        if (!in_array($hookName, $hooks[$hookTime]))
            $hooks[$hookTime] = $hookName;
    }
    
    function debug($obj)
    {
        Zend_Debug :: dump($obj);
    }
    
    function session()
    {
        $sessionName = md5_file(__file__);
        $session = new Zend_Session_Namespace(SESSION_NAME);
        return $session;
    }
    
    function makeExcel($tab, $table)
	{
		$table = _r(' ', '_', $table);
		$excel = '<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
		<meta name="ProgId" content="Excel.Sheet">
		<meta name="Generator" content="Microsoft Excel 11">
		<style id="Classeur1_17373_Styles">
		<!--table
			{mso-displayed-decimal-separator:"\,";
			mso-displayed-thousand-separator:" ";}
		.xl1517373
			{padding-top:1px;
			padding-right:1px;
			padding-left:1px;
			mso-ignore:padding;
			color:windowtext;
			font-size:10.0pt;
			font-weight:400;
			font-style:normal;
			text-decoration:none;
			font-family:Arial;
			mso-generic-font-family:auto;
			mso-font-charset:0;
			mso-number-format:General;
			text-align:general;
			vertical-align:bottom;
			mso-background-source:auto;
			mso-pattern:auto;
			white-space:nowrap;}
		.xl2217373
			{padding-top:1px;
			padding-right:1px;
			padding-left:1px;
			mso-ignore:padding;
			color:#FFFF99;
			font-size:10.0pt;
			font-weight:700;
			font-style:normal;
			text-decoration:none;
			font-family:Arial, sans-serif;
			mso-font-charset:0;
			mso-number-format:General;
			text-align:center;
			vertical-align:bottom;
			background:#003366;
			mso-pattern:auto none;
			white-space:nowrap;}
		-->
		</style>
	</head>

		<body>
		<!--[if !excel]>&nbsp;&nbsp;<![endif]-->

		<div id="Classeur1_17373" align="center" x:publishsource="Excel">

		<table x:str border="0" cellpadding="0" cellspacing="0" width=640 style="border-collapse:
		 collapse; table-layout: fixed; width: 480pt">
		 <col width="80" span=8 style="width: 60pt">
		 <tr height="17" style="height:12.75pt">
		  ##entetes##
		 </tr>
		 ##contenu##
		</table>
		</div>
	</body>
</html>';
		$tpl_entete = '<td class="xl2217373">##val##</td>';
		$tpl_td = '<td>##val##</td>';
		
		$entetes = array();
		
		foreach ($tab as $ligne)
		{
			foreach ($ligne as $c => $v)
			{
				if (!in_array($c, $entetes))
					$entetes[] = $c;
			}
		}
		$ent_xls = '';
		foreach ($entetes as $ent)
			$ent_xls .= _r('##val##', $ent, $tpl_entete);
		$excel = _r('##entetes##', $ent_xls, $excel);
		
		$cont_xls = '';
		foreach ($tab as $ligne)
		{
			$cont_xls .= '<tr>';
			foreach ($ligne as $c => $v)
            {
				if (is_utf8($v))
                    $v = utf8_decode($v);
                $cont_xls .= _r('##val##', $v, $tpl_td);
            }
			$cont_xls .= '</tr>';
		}
		
		$excel = _r('##contenu##', $cont_xls, $excel);
		header ("Content-type: application/excel");
		header ('Content-disposition: attachement; filename="export_' . $table . '_' . date('d_m_Y_H_i_s') . '.xls"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: 0");
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");
		die($excel);
	}
    
    function zend()
    {
        require_once 'Zend/Loader/Autoloader.php';
        $autoloader = Zend_Loader_Autoloader :: getInstance();
        $autoloader -> setFallbackAutoloader(true);
    }
    
    function viewRenderer($files = array())
    {
        if (!count($files))
        {
            $files = array(
				tpl()
            );
        }
        setvar('**htmlFiles**', $files);
    }
    
    function go404()
    {
        setvar('**page**', 404);
        setvar('**action**', 'index');
        $controller = controller :: getInstance();
        $htmlFiles = array(
				tpl()
			);
        setvar('**htmlFiles**', $htmlFiles);
        $controller -> html();
        exit;
    }
    
    function tpl()
    {
        $htmlPage = getvar('**page**') . '/';
        if (getvar('**action**') !== null)
           $htmlPage .= getvar('**action**');
        
        if (!is_file(DIR_VIEWS . $htmlPage . '.html'))
            go404();

        return $htmlPage;
    }
    
    function isEmail($email)
    {
        return Zend_Validate :: is($email, 'EmailAddress');
    }
    
    function cache($name, $value = '')
    {
        $fo = array(
            'lifetime' => 7200,
            'automatic_serialization' => true
        );
        
        $bo = array(
            'cache_dir' => DIR_CACHE
        );
        
        $cache = Zend_Cache :: factory(
            'Core',
            'File',
            $fo,
            $bo
        );
        
        $cached = $cache -> load($name);
        
        if (false === $cached && isset($value))
        {
            $cache -> save($value, $name);
            return $value;
        }
        if (false === $cached && !isset($value))
            return false;
        return $cached;
    }
    
    
    function putFunctionCache($fonction, $param = '')
	{
		if (is_array($param))
		{
			$res = call_user_func_array($fonction, $param);
			$param = implode(', ', $param);
		}
		else
			$res = $fonction($param);
		$name = md5($fonction . $param);
        cache($name, $res);
		return $res;
	}
	
	function callFunctionCache($fonction, $param = '')
	{
		if (is_array($param))
			$param = implode(', ', $param);
		$name = md5($fonction . $param);
        $cached = cache($name);
        if (false === $cached)
            return putFunctionCache($fonction, $param);
        else
            return $cached;
	}
    
    
    //formulaires
    function initCssForm()
    {
        $css = array(
                'ViewHelper',
                'Errors',
                array('HtmlTag', array('tag' => 'td')),
                array('Label', array('tag' => 'th')),
                array(array('tr' => 'HtmlTag'), array('tag' => 'tr'))
            );
        setvar('**cssForm**', $css);
    }
    
    function formHidden($form, $name, $value = '')
    {
        $$name = new Zend_Form_Element_Hidden($name);
        $$name -> setValue($value);
        $$name -> setAttrib('class', 'hidden');
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    function formInput($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Text($name);
        $$name -> setValue($value);
        $$name -> setAttrib('class', 'text');
        $$name -> setLabel(__($label));
        $$name -> setRequired($required);
        $$name -> addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    function formDate($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Text($name);
        $$name -> setValue($value);
        $$name -> setAttrib('class', 'text date_picker');
        $$name -> setLabel(__($label));
        $$name -> setRequired($required);
        $$name -> addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    function formPassword($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Password($name);
        $$name -> setValue($value);
        $$name -> setAttrib('class', 'text');
        $$name -> setLabel(__($label));
        $$name -> setRequired($required);
        $$name -> addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    function formHtml($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Textarea($name);
        $$name -> setValue($value);
        $$name -> setLabel(__($label));
        $$name -> setAttrib('class', 'wysiwygTiny');
        $$name -> setRequired($required);
        $$name -> addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    function formTextarea($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Textarea($name);
        $$name -> setValue($value);
        $$name -> setLabel(__($label));
        $$name -> setRequired($required);
        $$name -> addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    function formSelect($form, $name, $label = '', $required = true, $value = array())
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Select($name);
        $$name -> addMultiOptions($value);
        $$name -> setLabel(__($label));
        $$name -> setAttrib('class', 'styled');
        $$name -> setRequired($required);
        $$name -> addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name -> setDecorators(getvar('**cssForm**'));
        $form -> addElement($$name);
    }
    
    //
    
    function sanitForm($form)
    {
        $form = _r('<ul class="errors">', '<tr><td  colspan="2" class="errorForm">', $form);
        $form = _r('</ul>', '</td></tr>', $form);
        $form = _r('<li>', '', $form);
        $form = _r('</li>', '&nbsp;', $form);
        $form = _r('<dt id="challenge-label">&#160;</dt>', '', $form);
        $form = _r('<dd id="challenge-element">', '<tr><td  colspan="2">', $form);
        $form = _r('</dd>', '</td></tr>', $form);
        return $form;
    }
    
    function sanitsql($str)
	{
		if (strstr($str, '##'))
		{
			$str = _r('##', '', $str);
			switch ($str)
			{
				case 'now':
					$str = _r('now', 'NOW()', $str);
					break;
				default:
					$str = getvar($str);
					break;
			}
		}
		return mysql_real_escape_string($str);
	}
    
    function optionsPage($default)
    {
        $page = getvar('**page**');
        $limit = config('limit');
        
        $numPage = getvar('__numPage_' . $page . '__');
        if (null === $numPage)
        {
            $numPage = getvarget('numPage_' . $page);
            if (null === $numPage)
            {
                $numPage = getvarpost('numPage_' . $page);
                if (null === $numPage)
                    $numPage = getoption('numPage_' . $page);
            }
        }
        
        $order = getvar('__order_' . $page . '__');
        // die($order);
        if (null === $order)
        {
            $numPage = getvarget('order_' . $page);
            if (null === $order)
            {
                $order = getvarpost('order_' . $page);
                if (null === $order)
                    $order = getoption('order_' . $page);
            }
        }
        
        $sens = getvar('__sens_' . $page . '__');
        if (null === $sens)
        {
            $numPage = getvarget('sens_' . $page);
            if (null === $sens)
            {
                $sens = getvarpost('sens_' . $page);
                if (null === $sens)
                    $sens = getoption('sens_' . $page);
            }
        }
        
        if (null === $numPage)
            $numPage = 1;
        if (null === $order)
            $order = $default;
        if (null === $sens)
            $sens = 'ASC';
            
        $start = ($numPage * $limit) - $limit;
        
        setoption('numPage_' . $page, $numPage);
        setoption('order_' . $page, $order);
        setoption('sens_' . $page, strtolower($sens));
        setoption('start_' . $page, $start);
        
        return array($numPage, $order, $sens, $start);
    }
    
    function makeOrder($field)
    {
        $page = getvar('**page**');
        $action = getvar('**action**');
        
        $sens = getoption('sens_' . $page);
        $numPage = getoption('numPage_' . $page);
        $order = getoption('order_' . $page);
        $start = getoption('start_' . $page);
        
        if ($field == $order)
        {
            $img = URL_SITE . 'img/sort_' . $sens . '.png';
            $sensUrl = ($sens == 'asc') ? 'desc' : 'asc';
        }
        else
        {
            $img = URL_SITE . 'img/sort_both.png';
            $sensUrl = 'asc';
        }
        
        $options = array(
            'numPage_' . $page => $numPage,
            'order_' . $page => $field,
            'sens_' . $page => $sensUrl,
            'start_' . $page => $start
        );
        
        $url = makeUrl($page, $action, $options);
        $html = '<a href="' . $url . '"><img style="position: relative; top: 3px; left: 3px;" border="0" src="' . $img. '" alt="' . __('Ordonner') . '" title="' . __('Ordonner') . '" /></a>';
        return $html;
    }
    
    function insertDb($table, $tab)
	{
		$db = db();
		if (is_array($tab))
		{
			$q = "INSERT INTO $table SET datecrea = NOW(), datemodif = NOW(), ";
			foreach ($tab as $c => $v)
				$q .= "$c = '" . sanitsql($v) . "', ";
			$q = substr($q, 0, -2);
			$db -> requete($q);
			return true;
		}
		return false;
	}
	
	function updateDb($table, $tab, $where = '1 = 1')
	{
		$db = db();
		if (is_array($tab))
		{
			$q = "UPDATE $table SET datemodif = NOW(), ";
			foreach ($tab as $c => $v)
				$q .= "$c = '" . sanitsql($v) . "', ";
			$q = substr($q, 0, -2);
			$q .= ' WHERE ' . $where;
			$db -> requete($q);
			return true;
		}
		return false;
	}
	
	function updateDbId($table, $tab, $id)
	{
		return updateDb($table, $tab, 'id = ' . $id);
	}
	
	function deleteDb($table, $where = '1 = 1')
	{
		$db = db();
		$q = "DELETE FROM $table WHERE " . $where;
		$db -> requete($q);
		return true;
	}
	
	function deleteDbId($table, $id)
	{
		return deleteDb($table, 'id = ' . $id);
	}
	
	function emptyTable($table)
	{
		$db = db();
		$db -> requete("TRUNCATE TABLE $table");
		return true;
	}
    
    function appsession()
    {
        Zend_Session :: start();
    }
    
    function form($class)
    {
        if (is_file(DIR_MODELS . 'forms/' . $class . '.php'))
        {
            require_once(DIR_MODELS . 'forms/' . $class . '.php');
            $form = new $class;
            return $form;
        }
        return null;
    }
    
    function instantiate($class, $record) 
    {
		$object = new $class;
		
		foreach($record as $attr => $val)
			if(has_attribute($object, $attr))
				$object -> $attr = $val;
		return $object;
	}
    
    function has_attribute($class, $attribute) 
    {
		$object_vars = get_object_vars($class);
		return array_key_exists($attribute, $object_vars);
	}
    
    function purgeCache($force = false)
	{
		viderdossier(DIR_CACHE, $force);
	}
	
	function purgeOptions($force = false)
	{
        viderdossier(DIR_OPT, $force);
	}
    
    function viderdossier($dir, $force = false)
    {
        if (false === $force)
            $expire = 86400;
        else
            $expire = 0;
        $sepdn = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? '\\' : '/';
		if (is_dir($dir)) 
		{
			$objects = scandir($dir);
			foreach ($objects as $object) 
			{
				if ($object <> "." && $object <> "..") 
				{
					if (filetype($dir . $sepdn . $object) == "dir") 
						viderdossier($dir . $sepdn . $object, $force); 
					else
					{
						$now = time();
						$age = filemtime($dir . $sepdn . $object);
						$diff = $now - $age;
                        if ($diff >= $expire)
							@unlink($dir . $sepdn . $object);
					}
				}
			}
			reset($objects);
		}
    }
    
    function post($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $page = curl_exec($ch);
        curl_close($ch);
        return $page;
    }
    
    function push($url, $data)
    {
        $urlPush = $url;
        $suite = '';
        foreach ($data as $key => $value)
            $suite .= $key . '=' . urlencode($value) . '&';
        $suite = substr($suite, 0, -1);
        $urlPush .= '?' . $suite;
        return file_get_contents($urlPush);
    }
    
    function muLink($id)
    {
        return 'http://01php.fr/mu/?d=' . $id;
    }
    
    function mu($url, $name = '', $del = 1)
    {
        if (!isset($name))
            $name = md5($url);
        $urlPost = 'http://www.webz0ne.com/api/bigfile.php';
        $data = array(
            'url' => $url,
            'name' => $name,
            'del' => $del
        );
        $urlBack = post($urlPost, $data);
        if (strstr($urlBack, 'd='))
        {
            $urlBack = _r("\n", "", $urlBack);
            $urlBack = _r("\r", "", $urlBack);
            $urlBack = _r("\t", "", $urlBack);
            list($dummy, $code) = explode('d=', $urlBack, 2);
            return $code;
        }
        return false;
    }
    
    function cacheDb()
    {
        $cache = GP_dbcache :: getInstance();
        return $cache;
    }
    
    function model($model)
    {
        $file = DIR_MODELS . $model . '.ini';
        if (is_file($file))
        {
            $ini = new Zend_Config_Ini($file);
            return explode(',', $ini -> fields);
        }
        return array();
    }
    
    function attrField($model, $field, $attribut)
    {
        $file = DIR_MODELS . $model . '.ini';
        if (is_file($file))
        {
            $ini = new Zend_Config_Ini($file);
            return $ini -> $field -> $attribut;
        }
        return null;
    }
    
    function GPmail($to, $subject, $body, $from)
    {
        $mail = new Zend_Mail();
        $mail -> addHeader('X-Mailer', 'Apple Mail (2.936)');
        $mail -> setBodyText($body);
        $mail -> setBodyHtml($body);
        $mail -> setFrom($from);
        $mail -> addTo($to);
        $mail -> setSubject($subject);
        $res = $mail -> send();
        return $res;
    }
    
    function dbDoc($dbName, $dbColl)
    {
        $db = new GP_mongo('mongodb://' . CACHE_DB_USER . ':' . CACHE_DB_PASSWORD . '@' . CACHE_DB_HOST);
        $db -> db($dbName);
        $db -> coll($dbColl);
        return $db;
    }
    
    function dbCache()
    {
        $db = new GP_mongo('mongodb://' . CACHE_DB_USER . ':' . CACHE_DB_PASSWORD . '@' . CACHE_DB_HOST);
        $db -> db(CACHE_DB_NAME);
        $db -> coll(CACHE_DB_COLLECTION);
        return $db;
    }
    
    function cleanDbCache()
    {
        $db = dbCache();
        $min = time() - CACHE_DB_CACHETIME;
        $dateMin = array('$lt' => $min);
        return $db -> delete(array("timeAdd" => $dateMin));
    }
    
    function setDbCache($name, $value)
    {
        $db = dbCache();
        $ids = session_id();
        $db -> delete(array("session" => $ids, 'option' => $name));
        $db -> insert(array('session' => $ids, 'option' => $name, 'value' => $value));
    }
    
    function getDbCache($name)
    {
        $db = dbCache();
        $ids = session_id();
        $q = array();
        $q['queries'][] = array('session', '=', $ids);
        $q['queries'][] = array('option', '=', $name);
        $q['operators'][] = '&&';
        $res = $db -> query($q);
        if (count($res))
            foreach ($res as $record)
                return $record['value'];
        return null;
    }
	
	function load($className)
    {
        $dirClass = DIR_LIB . 'gp/class.' . $className . '.php';
        if (is_file($dirClass))
            require_once($dirClass);
    }
    
    function acc($str, $charset = 'utf-8')
	{
		$str = htmlentities($str, ENT_NOQUOTES, $charset);
		
		$str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
		$str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. '&oelig;'
		$str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
		return $str;
	}
    
    function go($url)
    {
        if (!headers_sent()) 
		{
			header('Location: ' . $url);
			exit;
		} 
		else
		{
			echo '<script type="text/javascript">';
			echo "\t" . 'window.location.href = "' . $url . '";';
			echo '</script>';
			echo '<noscript>';
			echo "\t" . '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
			echo '</noscript>';
			exit;
		}
    }
    
    function purge()
    {
        $purgeFile = DIR_TMP . 'purge.txt';
        if (!is_file($purgeFile))
            touch($purgeFile, 0777);
        $max = 43200; // 12 heures
        $age = filemtime($purgeFile);
        $diff = time() - $age;
        if ($diff >= $max)
        {
            purgeCache(true);
            purgeOptions(true);
            unlink($purgeFile);
            touch($purgeFile, 0777);
            file_put_contents($purgeFile, time());
        }
    }
    
    function connexion($login, $mdp)
    {
        $db = db();
        $q = "SELECT * FROM users WHERE login = '" . addslashes($login) . "' && mdp = '" . $mdp . "'";
        $res = $db -> fetchArray_one($q);
        if (count($res))
        {
            $user = new stdClass;
            $user -> uid = md5(uniqid(php_uname('n'), true));
            $user -> sessionId = session_id();
            foreach ($res as $key => $value)
                $user -> $key = $value;
            setoption('__user__', $user);
            return true;
        }
        return false;
    }
    
    function verifToken()
    {
        $token = token();
        $postToken = getvarpost('token');
        if ($token == $postToken)
            return true;
        return false;
    }
    
    function addCaptcha($form)
    {
        $seg = '<tr><td colspan="2">
<input type="submit"';

        $replace = '<tr><th id="captcha-label"><label for="captcha" class="required">'.__('Vérification').'</label></th><td>' . captcha() . '</td></tr>' . $seg;
        $form = _r($seg, $replace, $form);
        $js = "<script>
	var RecaptchaOptions = 
	{
	  theme : 'clean',
	  lang : 'fr'
	};
	</script>
";
        return $js . $form;
    }
    
    function captcha()
    {
        $config = getConfig();
        $publicKey = $config['reCaptcha.publicKey'];
        $captcha = recaptcha_get_html($publicKey);
        return $captcha;
    }
    
    function verifyCaptcha()
    {
        $config = getConfig();
        $privateKey = $config['reCaptcha.privateKey'];
        $verify = recaptcha_check_answer (
			$privateKey,
            $_SERVER["REMOTE_ADDR"],
            $_POST['recaptcha_challenge_field'],
            $_POST['recaptcha_response_field']
		);
        
        return $verify -> is_valid;
    }  
    
    
    function user()
    {
        $user = getoption('__user__');
        if (null === $user)
            return session_id();
        return $user;
    }
    
    function role()
    {
        return getUser('role');
    }
    
    function idUser()
    {
        return getUser('id');
    }
    
    function token()
    {
        return getUser();
    }
    
    function getUser($param = 'uid')
    {
        $user = user();
        if (is_object($user))
            return $user -> $param;
        return null;
    }
    
    function aff_fo($chaine)
	{
		if (!is_utf8($chaine))
			$chaine = utf8_encode($chaine);
		return sl($chaine);
	}
    
    function nettoie($chaine)
	{
		$chaine = strtolower($chaine);
		$chaine = acc($chaine);
		
		$chaine = _r(" ", '_', $chaine);
		$chaine = _r("'", '_', $chaine);
		$chaine = _r("(", '_', $chaine);
		$chaine = _r(")", '_', $chaine);
		$chaine = _r(";", '_', $chaine);
		$chaine = _r(",", '_', $chaine);
		$chaine = _r(":", '_', $chaine);
		$chaine = _r("!", '_', $chaine);
		$chaine = _r(".", '_', $chaine);
		$chaine = _r("?", '_', $chaine);
		$chaine = _r("/", '_', $chaine);
		$chaine = _r("*", '_', $chaine);
		$chaine = _r("-", '_', $chaine);
		$chaine = _r("+", '_', $chaine);
		$chaine = _r("[", '_', $chaine);
		$chaine = _r("]", '_', $chaine);
		$chaine = _r("{", '_', $chaine);
		$chaine = _r("}", '_', $chaine);
		$chaine = _r("=", '_', $chaine);
		$chaine = _r("@", '_', $chaine);
		$chaine = _r("#", '_', $chaine);
		
		$chaine = _r("_039_", '_', $chaine);
		$chaine = _r("_00128_", 'euro', $chaine);
		$chaine = _r("_00192_", 'a', $chaine);
		$chaine = _r("_00193_", 'a', $chaine);
		$chaine = _r("_00194_", 'a', $chaine);
		$chaine = _r("_00195_", 'a', $chaine);
		$chaine = _r("_00196_", 'a', $chaine);
		$chaine = _r("_00197_", 'a', $chaine);
		$chaine = _r("_00198_", 'a', $chaine);
		$chaine = _r("_00224_", 'a', $chaine);
		$chaine = _r("_00225_", 'a', $chaine);
		$chaine = _r("_00226_", 'a', $chaine);
		$chaine = _r("_00227_", 'a', $chaine);
		$chaine = _r("_00228_", 'a', $chaine);
		$chaine = _r("_00229_", 'a', $chaine);
		$chaine = _r("_00230_", 'a', $chaine);
		
		$chaine = _r("_00209_", 'n', $chaine);
		$chaine = _r("_00241_", 'n', $chaine);
		
		$chaine = _r("_00223_", 'ss', $chaine);
		
		$chaine = _r("_00199_", 'c', $chaine);
		$chaine = _r("_00231_", 'c', $chaine);
		
		$chaine = _r("_00201_", 'e', $chaine);
		$chaine = _r("_00232_", 'e', $chaine);
		$chaine = _r("_00200_", 'e', $chaine);
		$chaine = _r("_00202_", 'e', $chaine);
		$chaine = _r("_00203_", 'e', $chaine);
		$chaine = _r("_00233_", 'e', $chaine);
		$chaine = _r("_00234_", 'e', $chaine);
		$chaine = _r("_00235_", 'e', $chaine);
		
		$chaine = _r("_00204_", 'i', $chaine);
		$chaine = _r("_00205_", 'i', $chaine);
		$chaine = _r("_00206_", 'i', $chaine);
		$chaine = _r("_00207_", 'i', $chaine);
		$chaine = _r("_00236_", 'i', $chaine);
		$chaine = _r("_00237_", 'i', $chaine);
		$chaine = _r("_00238_", 'i', $chaine);
		$chaine = _r("_00239_", 'i', $chaine);
		
		$chaine = _r("_00210_", 'o', $chaine);
		$chaine = _r("_00211_", 'o', $chaine);
		$chaine = _r("_00212_", 'o', $chaine);
		$chaine = _r("_00213_", 'o', $chaine);
		$chaine = _r("_00214_", 'o', $chaine);
		$chaine = _r("_00216_", 'o', $chaine);
		$chaine = _r("_00240_", 'o', $chaine);
		$chaine = _r("_00241_", 'o', $chaine);
		$chaine = _r("_00242_", 'o', $chaine);
		$chaine = _r("_00243_", 'o', $chaine);
		$chaine = _r("_00244_", 'o', $chaine);
		$chaine = _r("_00245_", 'o', $chaine);
		$chaine = _r("_00246_", 'o', $chaine);
		$chaine = _r("_00248_", 'o', $chaine);
		
		$chaine = _r("_00217_", 'u', $chaine);
		$chaine = _r("_00218_", 'u', $chaine);
		$chaine = _r("_00219_", 'u', $chaine);
		$chaine = _r("_00220_", 'u', $chaine);
		$chaine = _r("_00249_", 'u', $chaine);
		$chaine = _r("_00250_", 'u', $chaine);
		$chaine = _r("_00251_", 'u', $chaine);
		$chaine = _r("_00252_", 'u', $chaine);
		
		$chaine = _r("_00221_", 'y', $chaine);
		$chaine = _r("_00253_", 'y', $chaine);
		$chaine = _r("_00254_", 'y', $chaine);
		$chaine = _r("_00255_", 'y', $chaine);
		
		$chaine = _r("__", '_', $chaine);
		$chaine = _r("__", '_', $chaine);
		$chaine = _r("__", '_', $chaine);
		
		$last = $chaine[strlen($chaine) - 1];
		if ($last == '_')
			$chaine = substr($chaine, 0, -1);
		return $chaine;
	}
    
    function __($str)
    {
        $lng = getoption('__lng__');
        $lngDefault = LNG_DEFAULT;
        if ($lng == $lngDefault) {
            return $str;
        }
        $trad = new GP_trad($lng);
        $strTrans = $trad->__($str);
        return $strTrans;
        // $ficTrad = DIR_TRAD . $lng . '.ini';
        // if (!is_file($ficTrad))
        // {
            // @touch($ficTrad);
            // @chmod($ficTrad, 0777);
        // }
        // $strIni = nettoie($str);
        // $trads = parse_ini_file($ficTrad);
        
        // if (null === $trads[$strIni])
        // {
            // $fp = fopen($ficTrad, 'a');
            // fwrite($fp, $strIni . ' = "' . $str . '"' . "\n");
            // fclose($fp);
            // return $str;
        // }
        // else
            // return $trads[$strIni];
    }
    
    function db()
    {
        $config = getConfig();
        $db = new GP_db($config['db.dsn'], $config['db.user'], $config['db.password']);
        return $db;
    }
    
    function getConfig()
    {
        return getvar('**config**');
    }
	
	function setvar($nom, $val, $force = true)
	{
		$gp_options = GP_options::getInstance();
		if (true === $force)
		{
			$gp_options -> delete($nom, $session);
			$gp_options -> record($nom, $val);
		}
		return true;
	}
    
    function getvartab($tabName, $key)
    {
        $tab = getvar($tabName);
        if (is_array($tab) && count($tab) && null !== $tab)
            if (isset($tab[$key]))
                return $tab[$key];
        return null;
    }
	
	function getvar($nom)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options -> get($nom);
	}
	
	function getvarpost($nom)
	{
		return getvar('post_' . $nom);
	}
	
	function getvarget($nom)
	{
		return getvar('get_' . $nom);
	}
	
	function getvarsession($nom)
	{
		return getvar('session_' . $nom);
	}
	
	function deloption($nom, $id = null)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options -> deloption($nom, $id);
	}
	
	function setoption($nom, $val, $id = null)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options -> setoption($nom, $val, $id);
	}
	
	function getoption($nom, $id = null)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options -> getoption($nom, $id);
	}
	
	function dossier_options($fic)
	{
		$dossier = substr($fic, -3);
		if (!is_dir(DIR_OPT . $dossier))
		{
			$oldumask = umask(0);
			mkdir(DIR_OPT . $dossier, 0777);
			umask($oldumask);
		}
		return $dossier . '/';
	}
	
	function get_post()
	{
		if(count($_POST))
		{
			foreach ($_POST as $c => $v)
				setvar('post_' .$c, $v);
		}
	}
	
	function get_get()
	{
		if(count($_GET))
		{
			foreach ($_GET as $c => $v)
				setvar('get_' .$c, $v);
		}
	}
	
	function get_session()
	{
		if(count($_SESSION))
		{
			foreach ($_SESSION as $c => $v)
				setvar('session_' .$c, $v);
		}
	}
    
    function hidden($form, $name, $value)
    {
        $css = array(
            'ViewHelper',
            'Errors',
            array('HtmlTag', array('tag' => 'td')),
            array('Label', array('tag' => 'th')),
            array(array('tr' => 'HtmlTag'), array('tag' => 'tr'))
        );
        $hidden = new Zend_Form_Element_Hidden($name);
        $hidden -> setValue($value);
        $hidden -> setAttrib('class', 'hidden');
        $hidden -> setDecorators($css);
        $form -> addElement($hidden);
    }
	
	function get_vars()
	{
		get_post();
		get_get();
		get_session();
	}
	
	function getPage()
	{
        $uri = $_SERVER['REQUEST_URI'];
        $uri = _r('.html', '', $uri);
        $tabUri = explode('/', $uri);
        $page = $tabUri[1];
        $action = $tabUri[2];
        if (count($tabUri) > 3)
        {
            for ($i = 3 ; $i < count($tabUri) ; $i += 2)
				setvar('__' .$tabUri[$i] . '__', $tabUri[$i + 1]);
        }
        
        if (!strlen($action))
            $action = 'index';
		
        if (!strlen($page))
		{
			$page = getvarpost('page');
			if (null === $page)
			{
				$page = getvarsession('page');
				if (null === $page)
					$page = PAGE_DEFAULT;
			}
		}
		
		if ($page == 'index')
			$page = PAGE_DEFAULT;
		
		if ($page <> 'logout')
            $page = (true === page_exists($page)) ? $page : 404;
        if(null === getoption("__user__") && $page <> 404 && $page <> 'forget' && $page <> 'login')
            $page = 'login';
		
        if ($page == 'logout')
        {
            $_SESSION = array();
            purgeOptions(true);
            $page = 'login';
        }
        
        setvar('**page**', $page);
        setvar('**action**', $action);
        
		return $page;
	}
	
	function page_exists($page)
	{
        return (is_file(DIR_CONTROLLERS . $page . '.php')) ? true : false;
	}
	
	function addError($error)
	{
		$errors = getvar('_errorsMessages');
		if (null === $errors)
			$errors = array();
		$errors[] = $error;
		$errors = array_unique($errors);
		setvar('_errorsMessages', $errors);
	}
	
	function getErrors()
	{
		return getvar('_errorsMessages');
	}
	
	function addTrace($trace)
	{
		$traces = getvar('_tracesMessages');
		if (null === $traces)
			$traces = array();
		$traces[] = $trace;
		$traces = array_unique($traces);
		setvar('_tracesMessages', $traces);
	}
	
	function getTraces()
	{
		return getvar('_tracesMessages');
	}
	
	function _r($a, $b, $string)
	{
		return str_replace($a, $b, $string);
	}
	
	function sl($string)
	{
		return stripslashes($string);
	}
	
	function is_utf8($string) 
	{
		return !strlen(
			preg_replace(
				  ',[\x09\x0A\x0D\x20-\x7E]'            
				. '|[\xC2-\xDF][\x80-\xBF]'             
				. '|\xE0[\xA0-\xBF][\x80-\xBF]'         
				. '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'  
				. '|\xED[\x80-\x9F][\x80-\xBF]'         
				. '|\xF0[\x90-\xBF][\x80-\xBF]{2}'      
				. '|[\xF1-\xF3][\x80-\xBF]{3}'          
				. '|\xF4[\x80-\x8F][\x80-\xBF]{2}'      
				. ',sS',
				'', 
				$string
			)
		);
	}
    
    function config($name = '')
    {
        $config = getvar('**config**');
        if (strlen($name))
            return $config[$name];
        return $config;
    }
    
    
    function select($table, $order, $sens, $start)
    {
        $db = db();
        $limit = config('limit');
        $q = "SELECT * FROM $table ORDER BY $order $sens LIMIT $start, $limit";
        return $db -> fetchArray($q);
    }
    
    function app()
    {
        $app = app::getInstance();
        return $app;
    }
    
    function action($controller, $action, $params = array())
    {
        $get = function($name){return getvar($name);};
		$set = function($name, $value){setvar($name, $value);};
        $post = function($name){return getvarpost($name);};
        $option = function($name){return getoption($name);};
        $app = app();
        
        if (count($params))
        {
            foreach ($params as $key => $value)
                setvar($key, $value);
        }
        $oldpage = getvar('**page**');
        $oldaction = getvar('**action**');
        setvar('**action**', $action);
        setvar('**page**', $controller);
        $scriptphp = DIR_CACHE . md5($controller . $action . token() . time()) . '.php';
		@touch($scriptphp);
		file_put_contents($scriptphp, $php);
		ob_start();
		require_once(DIR_CONTROLLERS . $controller . '.php');
        $objName = "controller_$controller";
        $obj = new $objName;
		$result = ob_get_contents();
		ob_end_clean();
		@unlink($scriptphp);
        setvar('**action**', $oldaction);
        setvar('**page**', $oldpage);
		return $result;
    }
    
    function partial($name, $page = '')
    {
        if (!strlen($page) || !isset($page))
            $page = getvar('**page**');
		$html = file_get_contents(DIR_VIEWS . 'partials/' . $page . '/' . $name . '.html');
        $result = parsephp($html);
		return $result;
    }
    
    function recupeval($php)
	{
		$get = function($name){return getvar($name);};
		$set = function($name, $value){setvar($name, $value);};
        $post = function($name){return getvarpost($name);};
        $option = function($name){return getoption($name);};
        $app = app();
        $scriptphp = DIR_CACHE . md5($php . time()) . '.php';
		@touch($scriptphp);
		file_put_contents($scriptphp, $php);
		ob_start();
		include($scriptphp);
		$result = ob_get_contents();
		ob_end_clean();
		@unlink($scriptphp);
		return $result;
	}
	
	function parsephp($val)
	{
		if (!is_utf8($val))
			$val = utf8_encode($val);
		$retour = _r('_("', '<?php echo __("', $val);
		$retour = _r('")_', '"); ?>', $retour);
        $retour = _r("_('", '<?php echo __("', $retour);
		$retour = _r("')_", '"); ?>', $retour);
		$retour = _r('{{=', '<?php echo ', $retour);
		$retour = _r('{{', '<?php ', $retour);
		$retour = _r('}}', '?>', $retour);
		
		$tab = explode('££', $retour);
		if (sizeof($tab) > 1)
		{
			for ($i = 1 ; $i < sizeof($tab) ; $i++)
			{
				$seg = trim($tab[$i]);
				list($chaine, $dummy) = explode('§§', $seg, 2);
				$retour = _r('££' . $chaine . '§§', '<?php echo __("' . sl($chaine) . '"); ?>', $retour);
			}
		}
		
		$retour = recupeval($retour);
		
		return $retour;
	}
    
    function makeUrl($page, $action = 'index', $params = array())
    {
        $url = URL_SITE . $page;
        if ('index' !== $action)
            $url .= '/' . $action;
        if (count($params))
        {
           $url .= '/';
           foreach ($params as $key => $value)
                $url .= $key . '/' . $value . '/';
           $url = substr($url, 0, -1);
        }
        
        $url .= '.html';
        return $url;
    }
    
    function habilitation()
    {
        $user = getoption('__user__');
        $page = getvar('**page**');
        $action = getvar('**action**');
        
        if (null !== $user && $page <> 404 && $page <> 'accueil' && $page <> 'forget')
        {
            $db = db();
            $role = $user -> role;
            if ($role == 1)
                setvar('**isAdmin**', true);
            if (1 <> $role)
            {
                setvar('**isAdmin**', false);
                $q = "SELECT id FROM habilitations WHERE page = '" . $page . "' && action = '" . $action . "' && role = $role";
                $res = $db -> fetchArray_one($q);
                if (!count($res))
                    setvar('**page**', 'nohabilitation');
            }
        }
    }
    
    function getMicrotime()
    {
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
    }
	
	function display()
	{
		habilitation();
        $page = getvar('**page**');
        $action = getvar('**action**');
        
        $_404 = (is_file(DIR_CONTROLLERS . $page . '.php')) ? false : true;
        if (true === $_404)
            setvar('**page**', 404);
        
        require_once(DIR_CONTROLLERS . $page . '.php');
        
        $class = 'controller_' . $page;
        $classMethods = get_class_methods($class);

        if (!in_array($action, $classMethods))
            go404();
            
        $display = new $class;
        return $display;
	}
	
	function getDirs($dirName)
	{
		$allDirs = array_filter(glob($dirName . '/*'), 'is_dir'); 
		foreach ($allDirs as $dir)
		{
			if (is_dir($dir))
				$allDirs = array_merge($allDirs, getDirs($dir));
		}
		return $allDirs;
	}
	
	function cleanDirs($dirs, $stack)
	{
		$return = array();
		foreach ($dirs as $dir)
		{
			if (!is_utf8($dir))
				$dir = utf8_encode($dir);
			$return[] = _r($stack, '', $dir);
		}
		
		sort($return);
		return $return;
	}
	
	function dossier_cache($fic)
	{
		$dossier = substr($fic, -3);
		if (!is_dir(DIR_CACHE . $dossier))
		{
			$oldumask = umask(0);
			mkdir(DIR_CACHE . $dossier, 0777);
			umask($oldumask);
		}
		return $dossier . '/';
	}	
	
	function parseXml($xml, $attributesKey = null, $childrenKey = null, $valueKey = null)
	{
		if (!is_object($xml))
            return null;
        if($childrenKey && !is_string($childrenKey))
			$childrenKey = '@children';
		if($attributesKey && !is_string($attributesKey))
			$attributesKey = '@attributes';
		if($valueKey && !is_string($valueKey))
			$valueKey = '@values';

		$return = array();
		$name = $xml -> getName();
		$_value = trim((string)$xml);
		
		if(!strlen($_value))
			$_value = null;

		if(null !== $_value)
		{
			if($valueKey)
				$return[$valueKey] = $_value;
			else
				$return = $_value;
		}

		$children = array();
		$first = true;
		foreach($xml -> children() as $elementName => $child)
		{
			$value = parseXml($child, $attributesKey, $childrenKey,$valueKey);
			if(isset($children[$elementName]))
			{
				if(is_array($children[$elementName]))
				{
					if($first)
					{
						$temp = $children[$elementName];
						unset($children[$elementName]);
						$children[$elementName][] = $temp;
						$first = 0;
					}
					$children[$elementName][] = $value;
				}
				else
					$children[$elementName] = array($children[$elementName], $value);
			}
			else
				$children[$elementName] = $value;
		}
		if($children)
		{
			if($childrenKey)
				$return[$childrenKey] = $children;
			else
				$return = array_merge($return,$children);
		}

		$attributes = array();
		foreach($xml -> attributes() as $name => $value)
			$attributes[$name] = trim($value);

		if($attributes)
		{
			if($attributesKey)
				$return[$attributesKey] = $attributes;
			else
				$return = array_merge($return, $attributes);
		}

		return $return; 
	}
    
    function applog($str)
    {
        $flux = @fopen(LOG_FILE, 'a', false);
        if (! $flux)
            throw new Exception('Impossible d\'ouvrir le flux');
         
        $redacteur = new Zend_Log_Writer_Stream($flux);
        $logger = new Zend_Log($redacteur);
        $logger -> info($str);
    }
    
    function pagination($page_courante, $total)
	{			
		$page = getvar('**page**');
        $action = getvar('**action**');
        $limite = config('limit');
        
        $sens = getoption('sens_' . $page);
        $page_courante = getoption('numPage_' . $page);
        $order = getoption('order_' . $page);
        $start = getoption('start_' . $page);
        
        $options = array(
            'numPage_' . $page => '##numPage##',
            'order_' . $page => $order,
            'sens_' . $page => $sens,
            'start_' . $page => $start
        );
        
        $url = makeUrl($page, $action, $options);
        
        
		$html = '<span class="page_numbers" id="page_numbers">';
				
		if ($page_courante > 1)
			$html .= '<a href="' . _r('##numPage##', 1, $url) . '"><img title="Aller page 1" alt="Aller page 1" src="' . URL_SITE . 'img/first.png" style="position: relative; top: 4px;" /></a>&nbsp;&nbsp;<a href="' . _r('##numPage##', ($page_courante - 1), $url) . '"><img style="position: relative; top: 4px;" title="Aller page ' . ($page_courante - 1) . '" alt="Aller page ' . ($page_courante - 1) . '" src="' . URL_SITE . 'img/previous.png" /></a>&nbsp;&nbsp;&nbsp;';
				
		$nbpages = ceil($total / $limite);
				
		if ($page_courante < 5)
		{
			$submax = 5;
			if ($submax > $nbpages)
				$submax = $nbpages;
					
			for ($i = 1 ; $i <= $submax ; $i++)
			{
				if ($i == $page_courante)
					$html .= '<span class="page_courante"><a href="#" onclick="return false;">' . $i . '</a></span>&nbsp;';
				else
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
			}
					
			if ($nbpages > $submax)
			{
				if ((($nbpages - 3) - $submax) > 1)
						$html .= '<strong>&hellip;</strong>&nbsp;';
							
				for ($i = $nbpages - 3 ; $i <= $nbpages ; $i++)
						$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
			}
		}
				
		else
		{
            if ($page_courante < $nbpages - 5)
            {
				for ($i = 1 ; $i <= 3 ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
						
				if ($page_courante - $i > 1)
					$html .= '<strong>&hellip;</strong>&nbsp;';
						
				for ($i = $page_courante - 1 ; $i <= $page_courante + 5 ; $i++)
				{
					if ($i == $page_courante)
						$html .= '<span class="page_courante"><a href="#" onclick="return false;">' . $i . '</a></span>&nbsp;';
					else
						$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
				}
						
				$debmin = $nbpages - 3;
						
				if ($debmin <= $page_courante + 5)
					$debmin = $page_courante + 6;
							
				if (($debmin - $i) > 1 && $debmin <> $nbpages)
					$html .= '<strong>&hellip;</strong>&nbsp;';
							
				for ($i = $debmin ; $i <= $nbpages ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
			}
			else
			{
				for ($i = 1 ; $i <= 3 ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
						
					$debmin = ($page_courante - 4 <= 3) ? 4 : $page_courante - 4;
						
				if ($debmin - 3 > 1)
					$html .= '<strong>&hellip;</strong>&nbsp;';
						
				for ($i = $debmin ; $i < $page_courante ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
							
				if ($page_courante - $i > 1)
					$html .= '<strong>&hellip;</strong>&nbsp;';
						
				for ($i = $page_courante ; $i <= $nbpages ; $i++)
				{
					if ($i == $page_courante)
							$html .= '<span class="page_courante"><a href="#" onclick="return false;">' . $i . '</a></span>&nbsp;';
					else
						$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
				}
			}
		}
			
		if ($page_courante < $nbpages)
				$html .= '&nbsp;&nbsp;&nbsp;<a href="' . _r('##numPage##', ($page_courante + 1), $url) . '"><img style="position: relative; top: 4px;" title="Aller page ' . ($page_courante + 1) . '" alt="Aller page ' . ($page_courante + 1) . '" src="' . URL_SITE . 'img/next.png" /></a>&nbsp;&nbsp;<a href="' . _r('##numPage##', $nbpages, $url) . '"><img style="position: relative; top: 4px;" title="Aller page ' . ($nbpages).'" alt="Aller page ' . $nbpages . '" src="'.URL_SITE.'img/last.png" /></a>';
		$html .= '</span>';
				
		return $html;
	}
?>